<?php

namespace App\Domain\Customer\Controllers;

use App\Domain\Customer\Requests\CustomerPost;
use App\Domain\Customer\Requests\UpdateCustomerPost;
use App\Domain\Customer\Services\CustomerService;
use App\Http\Controllers\Controller;
use App\Domain\Customer\Requests\LoginPost;
use App\Supports\Formatter\ResponseFormatter;
use App\Exceptions\BadRequestException;
use Illuminate\Http\Request;
use Tymon\JWTAuth\Facades\JWTAuth;


class CustomerController extends Controller
{

    /**
     * 登录获取token
     * @param Request $request
     * @return mixed
     * @throws \Illuminate\Validation\ValidationException
     */
    public function login(LoginPost $request)
    {
        $request->validated();
        $params = [
            'phone' => $request->input('phone'),
            'password' => $request->input('password'),
        ];

        $data = (new CustomerService())->Login($params);
        return $this->success([
            'token' => 'Bearer ' . $data['token']
        ]);

    }

    /**
     * 退出登录
     * @return mixed
     */
    public function logout()
    {
        auth('api')->logout();
        return $this->success([], '退出成功');
    }

    /**
     * 刷新token
     * @return mixed
     */
    public function refresh()
    {
        return $this->success([
            'access_token' => auth('api')->refresh(),
            'token_type' => 'bearer',
            'expires_in' => auth('api')->factory()->getTTL() * 60
        ], '刷新成功');
    }

    public function index()
    {
        $user = JWTAuth::parseToken()->touser();
        return $user['id'];
    }

    //更新密码
    public function update(UpdateCustomerPost $request, CustomerService $customerServic)
    {
        $param = $request->validated();
        $param['id'] = $this->index();
        $res = $customerServic->update($param);
        return $this->success($res);
    }


    //创建账号
    public function create(CustomerPost $request, CustomerService $customerService)
    {
        $param = $request->validated();

        $res = $customerService->createUser($param);

        return $this->success($res);
    }

    //短信验证码
    public function sendsms(Request $request, CustomerService $customerServic){
        $data = $customerServic->createsms($request['mobile']);
        return $data;
    }

}
